package com.lingxu.base.system.manage.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lingxu.base.common.api.vo.Result;
import com.lingxu.base.common.util.DateUtil;
import com.lingxu.base.common.util.UUID32Generator;
import com.lingxu.base.common.util.encrypt.MD5Utils;
import com.lingxu.base.config.LogInfoHandler;
import com.lingxu.base.system.manage.entity.*;
import com.lingxu.base.system.manage.service.*;
import com.lingxu.base.system.manage.util.GetUUIDUtil;
import com.lingxu.base.system.manage.vo.LoginUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


@Slf4j
@Api(tags="用户信息")
@RestController
@RequestMapping("/system/manage/sysUser")
public class SysUserController{

	@Resource
	private ISysUserService sysUserService;
	@Resource
	private ILoginService iLoginService;
	@Resource
	private ISysRoleService roleService;
	@Resource
	private ISysRoleMenuService roleMenuService;
	@Resource
	private ISysUserRoleService userRoleService;

	@Resource
	private ISysUserRoleService iSysUserRoleService;

	/**
	 * 分页列表查询
	 * 使用场景：选人场景，用户从属场景
	 *
	 * @param sysUser
	 * @return
	 */
	@ApiOperation(value="用户信息-分页列表查询", notes="用户信息-分页列表查询")
	@PostMapping(value = "/list")
	public Result<SysUser> queryPageList(@RequestBody SysUser sysUser) {
		Page<SysUser> page = new Page<SysUser>(sysUser.getPageNo(), sysUser.getPageSize());
		IPage<SysUser> pageList = sysUserService.queryPageList(page, sysUser);
		return Result.ok(pageList);
	}


	@ApiOperation(value="用户信息-用户密码重置", notes="用户信息-用户密码重置")
	@PostMapping(value = "/resetPassword")
	public Result<?> resetPassword(@RequestParam(name="ids")@ApiParam(value = "用户id(多个用逗号','隔开)",required = true) String ids){
		try {
			List<String> idList = Arrays.asList(ids.split(","));
			return iLoginService.resetPassword(idList);
		}catch (Exception e){
			e.printStackTrace();
			return Result.error("密码重置失败"+e.getMessage());
		}
	}


	 @ApiOperation(value="用户信息-本人修改密码", notes="用户信息-本人修改密码")
	 @PostMapping(value = "/updatePassword")
	 public Result<?> updatePassword(@RequestBody SysUserPassword sysUserPassword){
		 try {
			 return sysUserService.updatePassword(sysUserPassword.getUsername(),sysUserPassword.getOldpassword(),
					 sysUserPassword.getPassword(),sysUserPassword.getConfirmpassword());
		 }catch (Exception e){
			 e.printStackTrace();
			 return Result.error("本人修改密码失败"+e.getMessage());
		 }
	 }

	/**
	 * 添加
	 *
	 * @param sysUser
	 * @return
	 */
	@ApiOperation(value="用户信息-添加", notes="用户信息-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody SysUser sysUser) {
		String username = sysUser.getUsername();
		SysUser sysUser1 = sysUserService.getByName(username,"1");
		if(sysUser1!=null){
			return Result.ok("用户名已存在!");
		}
		String flag = "03";
		LoginUser userNow = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String id = UUID32Generator.generate();
		sysUser.setId(id);
		List<String> roleids = sysUser.getRoleids();
		//审批用户赋予权限01
		if(sysUser.getRoleids().contains("e7a692b87dc42f25e4b663c807674bd6")){
			flag = "01";
		}
		if(roleids!=null &&roleids.size()>0){
			for(String roleid:roleids){
				SysUserRole sysUserRole = new SysUserRole();
				sysUserRole.setId(GetUUIDUtil.getUUID());
				sysUserRole.setUserid(id);
				sysUserRole.setRoleid(roleid);
				sysUserRole.setCreateby(userNow.getId());
				sysUserRole.setCreatetime(new Date());
				iSysUserRoleService.save(sysUserRole);
			}
		}
		String passwordEncode = "";
		if(StringUtils.isNotBlank(sysUser.getPassword())){
			String password=sysUser.getPassword();
			passwordEncode = MD5Utils.Md5Encrypt(password);
			sysUser.setPassword(passwordEncode);
		}
		sysUser.setStatus("1");
		sysUser.setIsuse("1");
		sysUser.setIsdel("0");
		sysUser.setCreatetime(new Date());
		sysUser.setCreateby(userNow.getId());
		//保存日志
		String content = "新增用户【" + sysUser.getName() +"】,登录用户名为：【" + sysUser.getUsername() + "】";
		new LogInfoHandler().setLogInfoHandler(2,2, content);
		sysUserService.save(sysUser);
		//同时新增至建模用户表
		TSysUser tSysUser = new TSysUser();
		tSysUser.setId(id);
		tSysUser.setUsername(sysUser.getName());
		tSysUser.setAccount(sysUser.getUsername());
		tSysUser.setFlag(flag);
		tSysUser.setStatus("01");
		tSysUser.setDeptid(sysUser.getDeptid());
		tSysUser.setDeptname(sysUser.getDeptname());
		tSysUser.setPassword(passwordEncode);
		tSysUser.setIdnumber(StringUtils.isEmpty(sysUser.getIdcard()) ? null : sysUser.getIdcard());
		tSysUser.setCreatetime(DateUtil.getDateTime());
		tSysUser.setRegion(sysUser.getRegion());
		tSysUser.setRegionName(sysUser.getRegionName());
		sysUserService.insertTSysUser(tSysUser);
		return Result.ok("添加成功!");
	}
	
	/**
	 * 编辑
	 *
	 * @param sysUser
	 * @return
	 */
	@ApiOperation(value="用户信息-编辑", notes="用户信息-编辑")
	@PostMapping(value = "/edit")
	public Result<?> edit(@RequestBody SysUser sysUser) {
		LoginUser userNow = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if(StringUtils.isEmpty(sysUser.getId())){
			return Result.error("参数[id]不可以为空");
		}
		iSysUserRoleService.cancelUserRolesAll(sysUser.getId());
		List<String> roleids = sysUser.getRoleids();

//		List<SysRole> sysRoles = sysUser.getYfprole();

		if(roleids!=null &&roleids.size()>0){
			for(String roleid:roleids){
				SysUserRole sysUserRole = new SysUserRole();
//				sysUserRole.setId(GetUUIDUtil.getUUID());
				sysUserRole.setUserid(sysUser.getId());
				sysUserRole.setRoleid(roleid);
				sysUserRole.setCreateby(userNow.getId());
				sysUserRole.setCreatetime(new Date());
				iSysUserRoleService.save(sysUserRole);
			}
		}
		sysUserService.edit(sysUser);
		//保存日志
		String content = "修改用户【" + sysUser.getName() +"】";
		new LogInfoHandler().setLogInfoHandler(2,3, content);
		return Result.ok("修改成功!");
	}
	@ApiOperation(value="用户信息-根据ID获取用户信息", notes="用户信息-根据ID获取用户信息")
	@GetMapping(value = "/getSysUserInfo")
	public Result<?> getSysUserInfo(@RequestParam(name="id")@ApiParam(value = "用户id",required = true) String id) {

		SysUser sysUser = sysUserService.getById(id);
		List<String> roleids = iSysUserRoleService.getSysRoleIDExistByUserid(id);
		List<SysRole> yfprole = iSysUserRoleService.getSysRoleExistByUserid(id);
		List<SysRole> wprrole = iSysUserRoleService.getSysRoleNotExistByUserid(id);
		sysUser.setRoleids(roleids);
		sysUser.setYfprole(yfprole);
		sysUser.setWprrole(wprrole);
		return Result.ok(sysUser);
	}
	
	/**
	 * 通过id删除
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="用户信息-通过id删除", notes="用户信息-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id")@ApiParam(value = "用户id",required = true) String id) {

		SysUser sysUser = sysUserService.getById(id);
		iSysUserRoleService.cancelUserRolesAll(id);
		sysUserService.removeById(id);

		//保存日志
		String content = "删除用户【" + sysUser.getName() +"】";
		new LogInfoHandler().setLogInfoHandler(2,4, content);
		return Result.ok("删除成功!");
	}

	
	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 */
	@ApiOperation(value="用户信息-批量删除", notes="用户信息-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids")@ApiParam(value = "用户id(多个用逗号','隔开)",required = true) String ids) {
		List<String> idList = Arrays.asList(ids.split(","));

		String name = "";
		String notDelName = "";
		List<String> idDelList = new ArrayList<>();
		for(String id:idList){
			SysUser sysUser = sysUserService.getById(id);
			//20250312存在模型和上传数据的用户不允许删除
			if(sysUserService.findExistModelsOrData(id) > 0){
				notDelName+=sysUser.getName()+" ";
			}else{
				name+=sysUser.getName()+" ";
				idDelList.add(id);
			}
		}
		//保存日志
		String content = "";
		if(StringUtils.isNotBlank(notDelName) && StringUtils.isNotBlank(name)){
			content = "删除用户【" + name+"】成功,用户【" + notDelName+"】存在未删除的模型或数据,请删除后,才可以删除此用户";
		}else if(StringUtils.isNotBlank(notDelName) && StringUtils.isBlank(name)){
			content = "未能删除用户,用户【" + notDelName+"】存在未删除的模型或数据,请删除后,才可以删除此用户";
		}else{
			content = "删除用户【" + name+"】成功";
		}
		new LogInfoHandler().setLogInfoHandler(2,4, content);
		return this.sysUserService.deleteBatch(idDelList,content);
	}
	
	/**
	 * 通过id查询
	 *
	 * @param userId
	 * @return
	 */
	@ApiOperation(value="用户信息-通过id查询", notes="用户信息-通过id查询")
	@PostMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="userId")@ApiParam(value = "用户id",required = true) String userId) {
		return sysUserService.getOneById(userId);
	}

	@ApiOperation(value="用户信息-通过部门id查询", notes="用户信息-通过部门id查询")
	@PostMapping(value = "/queryByDeptid")
	public Result<?> queryByDeptid(@RequestParam(name="deptid")@ApiParam(value = "部门id",required = true) String deptid) {
		return sysUserService.queryByDeptid(deptid);
	}


	 @ApiOperation("一周内未修改密码提示")
	 @PostMapping(value = "/findNotModifyPassWordByWeek")
	 public Result findNotModifyPassWordByWeek(String userId){
		 return sysUserService.findNotModifyPassWordByWeek(userId);
	 }

	 @ApiOperation("修改密码最后一次修改时间")
	 @PostMapping(value = "/updateLastPwdTime")
	 public Result updateLastPwdTime(String userId){
		 SysUser sysUser = new SysUser();
		 sysUser.setId(userId);
		 sysUser.setLastupdpwdtime(new Date());
		 boolean b = sysUserService.updateById(sysUser);
		 if(b){
			 return Result.ok("操作成功");
		 }
		 return Result.error("操作失败");
	 }


//	 @PostMapping(value = "/findDefaultPwd")
//	 public Result findDefaultPwd(String userId){
//		 return sysUserService.findDefaultPwd(userId);
//	 }

	@ApiOperation(value="用户信息-激活与锁定", notes="用户信息-激活与锁定")
	@PostMapping(value = "/updateIsUse")
	public Result<?> updateIsUse(@RequestParam(name="ids")@ApiParam(value = "用户ids",required = true) String ids,@RequestParam(name="isuse")@ApiParam(value = "激活状态（0：锁定；1激活；）",required = true)String isuse) {
		if(ids.contains(",")){
			List<String> idlist = Arrays.asList(ids.split(","));
			String content = "用户【";
			for(String id:idlist){
				sysUserService.updateIsUse(id,isuse);
				SysUser sysUser = sysUserService.getById(id);
				content+=sysUser.getName()+" ";

			}
			if("1".equals(isuse)){
				content += "】账号激活";
				new LogInfoHandler().setLogInfoHandler(2,3, content);
			}
			if("0".equals(isuse)){
				content += "】账号锁定";
				new LogInfoHandler().setLogInfoHandler(2,3, content);
			}
		}else{
			sysUserService.updateIsUse(ids,isuse);
			SysUser sysUser = sysUserService.getById(ids);
			String content = "";
			if("1".equals(isuse)){
				content = "【" + sysUser.getName() +"】账号激活";
				new LogInfoHandler().setLogInfoHandler(2,3, content);
			}
			if("0".equals(isuse)){
				content = "用户【" + sysUser.getName() +"】账号锁定";
				new LogInfoHandler().setLogInfoHandler(2,3, content);
			}
		}
		return Result.ok("操作成功！");
	}
}
